<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="修改密码"
      width="480px"
      center
      draggable
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
      >
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="account">
              <el-input v-model="formValue.account" placeholder="账号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nikename">
              <el-input v-model="formValue.nikename" placeholder="昵称"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="旧密码" prop="oldpassword">
              <el-input
                type="password"
                v-model="formValue.oldpassword"
                placeholder="旧密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="新密码" prop="password">
              <el-input
                type="password"
                v-model="formValue.password"
                placeholder="新密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="确认密码" prop="verifypassword">
              <el-input
                type="password"
                v-model="formValue.verifypassword"
                placeholder="确认密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="text-align: center">
          <el-button type="primary" @click="submit(formRef)"> 保存 </el-button>
          <el-button @click="reset">重置</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus'

import { changePassword } from '@/apis/user.js'
import { useAuthStore } from '@/stores/user'
import router from '@/router/index'
const store = useAuthStore()

interface RuleForm {
  id: string
  oldpassword: string
  password: string
  verifypassword: string
}

const formRef = ref<FormInstance>()

let formValue = ref<RuleForm>({
  id: '',
  oldpassword: '',
  password: '',
  verifypassword: ''
})

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,12}$/
    if (!reg.test(value)) {
      callback(new Error('密码必须包含数字、字母，且在6~12位之间'))
    } else {
      callback()
    }
  }
}
const validateVerifyPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (value != formValue.value.password) {
      callback(new Error('输入的密码不一致'))
    } else {
      callback()
    }
  }
}

const rules = reactive<FormRules<RuleForm>>({
  // account: [
  //   { required: true, message: '请输入账号', trigger: 'blur' },
  //   { min: 3, max: 5, message: '长度在3~5位字符', trigger: 'blur' }
  // ],
  // nikename: [
  //   { required: true, message: '请输入昵称', trigger: 'blur' },
  //   { min: 3, max: 5, message: '长度在3~5位字符', trigger: 'blur' }
  // ],
  oldpassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword }],
  verifypassword: [{ required: true, validator: validateVerifyPassword }]
})

let dialogVisible = ref(false)

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`
}))

let userId = ref()

function open(id) {
  formValue.value = {
    id: '',
    oldpassword: '',
    password: '',
    verifypassword: ''
  }

  userId.value = id
  dialogVisible.value = true
}

function reset() {
  if (!formRef) return
  formRef.value.resetFields()
}

function baoCun() {
  ElMessageBox.confirm('修改密码后需要重新登录，确定要修改密码？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      changePassword({
        id: userId.value,
        oldpassword: formValue.value.oldpassword,
        password: formValue.value.password
      })
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '修改成功'
            })

            store.setAuth(false)
            store.setUser()
            store.setPermission()
            store.setToken()

            router.replace({
              path: '/login'
            })

            dialogVisible.value = false
          } else {
            ElMessage({
              type: 'error',
              message: '旧密码错误'
            })
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消修改'
      })
    })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      baoCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
</style>